const Router = require('koa-router')
const { Order, OrderItem, Customer, Product, Inventory, sequelize } = require('../models')
const auth = require('../middleware/auth')
const { Op } = require('sequelize')

const router = new Router({ prefix: '/api' })

// 生成订单编号
const generateOrderNo = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0')
  return `ORD${year}${month}${day}${random}`
}

// 获取订单列表
router.get('/orders', auth.requirePermission('order:read'), async (ctx) => {
  try {
    const {
      page = 1,
      size = 10,
      search = '',
      customer_id,
      status,
      date_from,
      date_to,
      sort = 'created_at',
      order = 'DESC'
    } = ctx.query

    const offset = (page - 1) * size
    const where = {}

    // 搜索条件
    if (search) {
      where[Op.or] = [
        { order_no: { [Op.like]: `%${search}%` } },
        { '$customer.name$': { [Op.like]: `%${search}%` } }
      ]
    }

    if (customer_id) {
      where.customer_id = customer_id
    }

    if (status) {
      where.status = status
    }

    // 日期范围查询
    if (date_from && date_to) {
      where.created_at = {
        [Op.between]: [new Date(date_from), new Date(date_to)]
      }
    } else if (date_from) {
      where.created_at = {
        [Op.gte]: new Date(date_from)
      }
    } else if (date_to) {
      where.created_at = {
        [Op.lte]: new Date(date_to)
      }
    }

    const { count, rows } = await Order.findAndCountAll({
      where,
      include: [
        {
          model: Customer,
          as: 'customer',
          attributes: ['id', 'name', 'contact_person', 'phone']
        },
        {
          model: OrderItem,
          as: 'items',
          attributes: ['id', 'quantity', 'unit_price', 'line_total'],
          include: [
            {
              model: Product,
              as: 'product',
              attributes: ['id', 'name', 'sku']
            }
          ]
        }
      ],
      order: [[sort, order.toUpperCase()]],
      limit: parseInt(size),
      offset
    })

    ctx.body = {
      code: 200,
      message: '获取订单列表成功',
      data: {
        list: rows,
        total: count,
        page: parseInt(page),
        size: parseInt(size)
      }
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ctx.body = {
      code: 500,
      message: '获取订单列表失败',
      error: error.message
    }
  }
})

// 获取订单详情
router.get('/orders/:id', auth.requirePermission('order:read'), async (ctx) => {
  try {
    const { id } = ctx.params

    const order = await Order.findByPk(id, {
      include: [
        {
          model: Customer,
          as: 'customer'
        },
        {
          model: OrderItem,
          as: 'items',
          include: [
            {
              model: Product,
              as: 'product'
            }
          ]
        }
      ]
    })

    if (!order) {
      ctx.status = 404
      ctx.body = {
        code: 404,
        message: '订单不存在'
      }
      return
    }

    ctx.body = {
      code: 200,
      message: '获取订单详情成功',
      data: order
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ctx.body = {
      code: 500,
      message: '获取订单详情失败',
      error: error.message
    }
  }
})

// 创建订单
router.post('/orders', auth.requirePermission('order:create'), async (ctx) => {
  const transaction = await sequelize.transaction()
  
  try {
    const {
      customer_id,
      items,
      discount = 0,
      shipping_fee = 0,
      notes
    } = ctx.request.body

    // 验证必填字段
    if (!customer_id || !items || !Array.isArray(items) || items.length === 0) {
      ctx.status = 400
      ctx.body = {
        code: 400,
        message: '客户ID和订单项为必填项'
      }
      return
    }

    // 验证客户是否存在
    const customer = await Customer.findByPk(customer_id)
    if (!customer) {
      ctx.status = 400
      ctx.body = {
        code: 400,
        message: '客户不存在'
      }
      return
    }

    // 验证订单项和计算总金额
    let line_total = 0
    const validatedItems = []

    for (const item of items) {
      const { product_id, quantity, unit_price } = item
      
      if (!product_id || !quantity || quantity <= 0) {
        await transaction.rollback()
        ctx.status = 400
        ctx.body = {
          code: 400,
          message: '订单项信息不完整'
        }
        return
      }

      // 验证产品是否存在
      const product = await Product.findByPk(product_id)
      if (!product) {
        await transaction.rollback()
        ctx.status = 400
        ctx.body = {
          code: 400,
          message: `产品ID ${product_id} 不存在`
        }
        return
      }

      // 检查库存
      const inventory = await Inventory.findOne({ where: { product_id } })
      if (!inventory || inventory.quantity < quantity) {
        await transaction.rollback()
        ctx.status = 400
        ctx.body = {
          code: 400,
          message: `产品 ${product.name} 库存不足`
        }
        return
      }

      const itemPrice = unit_price || product.price
      const itemSubtotal = quantity * itemPrice
      line_total += itemSubtotal

      validatedItems.push({
        product_id,
        quantity,
        unit_price: itemPrice,
        line_total: itemSubtotal
      })
    }

    // 计算总金额
    const total_amount = line_total - discount + shipping_fee

    // 创建订单
    const order = await Order.create({
      order_no: generateOrderNo(),
      customer_id,
      line_total,
      discount: parseFloat(discount),
      shipping_fee: parseFloat(shipping_fee),
      total_amount,
      status: 'pending',
      notes,
      created_by: ctx.state.user.id
    }, { transaction })

    // 创建订单项
    for (const item of validatedItems) {
      await OrderItem.create({
        ...item,
        order_id: order.id
      }, { transaction })

      // 更新库存（预留库存）
      await Inventory.increment(
        { reserved_quantity: item.quantity },
        { where: { product_id: item.product_id }, transaction }
      )
    }

    await transaction.commit()

    // 获取完整的订单信息
    const fullOrder = await Order.findByPk(order.id, {
      include: [
        {
          model: Customer,
          as: 'customer'
        },
        {
          model: OrderItem,
          as: 'items',
          include: [
            {
              model: Product,
              as: 'product'
            }
          ]
        }
      ]
    })

    ctx.body = {
      code: 200,
      message: '创建订单成功',
      data: fullOrder
    }
  } catch (error) {
    await transaction.rollback()
    console.error('创建订单失败:', error)
    ctx.body = {
      code: 500,
      message: '创建订单失败',
      error: error.message
    }
  }
})

// 更新订单状态
router.put('/orders/:id/status', auth.requirePermission('order:update'), async (ctx) => {
  const transaction = await sequelize.transaction()
  
  try {
    const { id } = ctx.params
    const { status } = ctx.request.body

    if (!status) {
      ctx.status = 400
      ctx.body = {
        code: 400,
        message: '状态为必填项'
      }
      return
    }

    const order = await Order.findByPk(id, {
      include: [
        {
          model: OrderItem,
          as: 'items'
        }
      ]
    })

    if (!order) {
      ctx.status = 404
      ctx.body = {
        code: 404,
        message: '订单不存在'
      }
      return
    }

    const oldStatus = order.status

    // 状态流转验证
    const validTransitions = {
      'pending': ['confirmed', 'cancelled'],
      'confirmed': ['shipped', 'cancelled'],
      'shipped': ['completed'],
      'completed': [],
      'cancelled': []
    }

    if (!validTransitions[oldStatus]?.includes(status)) {
      await transaction.rollback()
      ctx.status = 400
      ctx.body = {
        code: 400,
        message: `无法从 ${oldStatus} 状态更新为 ${status}`
      }
      return
    }

    // 更新订单状态
    await order.update({ status }, { transaction })

    // 根据状态变化更新库存
    if (status === 'confirmed' && oldStatus === 'pending') {
      // 确认订单：从预留库存转为实际出库
      for (const item of order.items) {
        await Inventory.decrement(
          { quantity: item.quantity, reserved_quantity: item.quantity },
          { where: { product_id: item.product_id }, transaction }
        )
      }
    } else if (status === 'cancelled') {
      // 取消订单：释放预留库存
      for (const item of order.items) {
        await Inventory.decrement(
          { reserved_quantity: item.quantity },
          { where: { product_id: item.product_id }, transaction }
        )
      }
    }

    await transaction.commit()

    ctx.body = {
      code: 200,
      message: '更新订单状态成功',
      data: order
    }
  } catch (error) {
    await transaction.rollback()
    console.error('更新订单状态失败:', error)
    ctx.body = {
      code: 500,
      message: '更新订单状态失败',
      error: error.message
    }
  }
})

// 删除订单
router.delete('/orders/:id', auth.requirePermission('order:delete'), async (ctx) => {
  const transaction = await sequelize.transaction()
  
  try {
    const { id } = ctx.params

    const order = await Order.findByPk(id, {
      include: [
        {
          model: OrderItem,
          as: 'items'
        }
      ]
    })

    if (!order) {
      ctx.status = 404
      ctx.body = {
        code: 404,
        message: '订单不存在'
      }
      return
    }

    // 只能删除待处理或已取消的订单
    if (!['pending', 'cancelled'].includes(order.status)) {
      ctx.status = 400
      ctx.body = {
        code: 400,
        message: '只能删除待处理或已取消的订单'
      }
      return
    }

    // 如果是待处理状态，需要释放预留库存
    if (order.status === 'pending') {
      for (const item of order.items) {
        await Inventory.decrement(
          { reserved_quantity: item.quantity },
          { where: { product_id: item.product_id }, transaction }
        )
      }
    }

    // 删除订单项
    await OrderItem.destroy({ where: { order_id: id }, transaction })
    
    // 删除订单
    await order.destroy({ transaction })

    await transaction.commit()

    ctx.body = {
      code: 200,
      message: '删除订单成功'
    }
  } catch (error) {
    await transaction.rollback()
    console.error('删除订单失败:', error)
    ctx.body = {
      code: 500,
      message: '删除订单失败',
      error: error.message
    }
  }
})

// 获取订单统计信息
router.get('/orders/stats/summary', auth.requirePermission('order:read'), async (ctx) => {
  try {
    const { date_from, date_to } = ctx.query
    
    const where = {}
    if (date_from && date_to) {
      where.created_at = {
        [Op.between]: [new Date(date_from), new Date(date_to)]
      }
    }

    const orders = await Order.findAll({
      where,
      attributes: ['id', 'total_amount', 'status']
    })

    const stats = {
      total_orders: orders.length,
      total_amount: orders.reduce((sum, order) => sum + parseFloat(order.total_amount || 0), 0),
      pending_orders: orders.filter(order => order.status === 'pending').length,
      confirmed_orders: orders.filter(order => order.status === 'confirmed').length,
      shipped_orders: orders.filter(order => order.status === 'shipped').length,
      completed_orders: orders.filter(order => order.status === 'completed').length,
      cancelled_orders: orders.filter(order => order.status === 'cancelled').length
    }

    ctx.body = {
      code: 200,
      message: '获取订单统计信息成功',
      data: stats
    }
  } catch (error) {
    console.error('获取订单统计信息失败:', error)
    ctx.body = {
      code: 500,
      message: '获取订单统计信息失败',
      error: error.message
    }
  }
})

module.exports = router